package com.matrix.storage.utils;

public class FileUtil {

    public static final double KB = 1024.0;

    public static String getFileExtension(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return "";
        }
        int lastDotIndex = fileUrl.lastIndexOf('.');
        if (lastDotIndex > 0 && lastDotIndex < fileUrl.length() - 1) {
            return fileUrl.substring(lastDotIndex + 1);
        } else {
            return "";
        }
    }

    /**
     * 正确的格式包含mp4、mp3、jgp, jpeg，avi
     * @param fileUrl
     * @return
     */
    public static boolean isValidFile(String fileUrl) {
        if (isVideo(fileUrl) || isImage(fileUrl) || isAudio(fileUrl)) {
            return true;
        } else {
            return false;
        }
    }

    public static String fileSizeStr(double fileLength) {
        if (fileLength / KB >= 1 && fileLength / KB <= 1024) {
            double len = fileLength / KB;
            len = Math.round(len * 100.00) / 100.00;
            return len + "KB";
        } else if (fileLength / KB / KB >= 1 && fileLength / KB / KB <= 1024) {
            double len = fileLength / KB / KB;
            len = Math.round(len * 100.00) / 100.00;
            return len + "M";
        } else if (fileLength >= 0 && fileLength <= 1024) {
            return fileLength + "b";
        } else if (fileLength / KB / KB / KB >= 1 && fileLength / KB / KB / KB <= 1024) {
            double len = fileLength / KB / KB / KB;
            len = Math.round(len * 100.00) / 100.00;
            return len + "G";
        } else if (fileLength / KB / KB / KB / KB >= 1 && fileLength / KB / KB / KB / KB <= 1024) {
            double len = fileLength / KB / KB / KB / KB;
            len = Math.round(len * 100.00) / 100.00;
            return len + "T";
        }
        return fileLength + "B";
    }

    public static boolean isVideo(String fileUrl) {
        String extension = getFileExtension(fileUrl);
        return extension.equalsIgnoreCase("mp4") || extension.equalsIgnoreCase("avi");
    }

    public static boolean isImage(String fileUrl) {
        String extension = getFileExtension(fileUrl);
        return extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("png");
    }

    public static boolean isAudio(String fileUrl) {
        String extension = getFileExtension(fileUrl);
        return extension.equalsIgnoreCase("mp3") || extension.equalsIgnoreCase("wav");
    }

}
